package com.zhiziai.aiproxy.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.transfer.Transfer;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferProgress;
import com.qcloud.cos.transfer.Upload;
import com.zhiziai.aiproxy.constants.Dict;
import com.zhiziai.aiproxy.constants.UploadType;
import com.zhiziai.aiproxy.utils.FileUtil;
import com.zhiziai.aiproxy.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author: liuxinyu06
 * @description: 上传service
 * @create: 2022-08-15
 **/
@Slf4j
@Service
public class UploadService {

    @Autowired
    private TransferManager transferManager;

    public String upload(Long userId, String url,String type) throws Exception{
        Preconditions.checkArgument(StringUtils.isNotEmpty(type), "上传类型为空");
        UploadType uploadType = UploadType.getByType(type);
        Preconditions.checkArgument(uploadType != null, "上传类型为空");
        File file = FileUtil.getFile(url);
        String key = MD5Util.calcMD5(userId+"")
                + uploadType.getPath() + file.getName();
        String imgUrl = upload(key,file, Dict.COS_BUCKETNAME);
        Preconditions.checkArgument(StringUtils.isNotEmpty(imgUrl),"上传失败");
        return imgUrl;
    }

    public String upload(String key,File file,String bucket) throws Exception{
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file);
        try {
            // 返回一个异步结果Upload, 可同步的调用waitForUploadResult等待upload结束, 成功返回UploadResult, 失败抛出异常.
            long startTime = System.currentTimeMillis();
            Upload upload = transferManager.upload(putObjectRequest);
//            showTransferProgress(upload);
            UploadResult uploadResult = upload.waitForUploadResult();
            long endTime = System.currentTimeMillis();
            log.info("upload used time:{}, uploadResult {}",(endTime - startTime) / 1000, JSONObject.toJSONString(uploadResult));
//            transferManager.shutdownNow();
            return Dict.COS_DNS + key;
        } catch (Exception e) {
            log.error("upload error ", e);
        }
        return null;
    }

    private static void showTransferProgress(Transfer transfer) {
        System.out.println(transfer.getDescription());
        do {
            TransferProgress progress = transfer.getProgress();
            long so_far = progress.getBytesTransferred();
            long total = progress.getTotalBytesToTransfer();
            double pct = progress.getPercentTransferred();
            System.out.printf("[%d / %d] = %.02f%%\n", so_far, total, pct);
        } while (transfer.isDone() == false);
        System.out.println(transfer.getState());
    }

    /**
     * 用缓冲区来实现这个转换, 即创建临时文件
     * 使用 MultipartFile.transferTo()
     *
     * @param multipartFile
     * @return
     */
    private static File transferToFile(MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String prefix = originalFilename.split("\\.")[0];
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        File file = File.createTempFile(MD5Util.calcMD5(prefix), suffix);
        multipartFile.transferTo(file);
        return file;
    }


    public static void main(String[] args) {
        File file = new File("/Users/liuxinyu/Desktop/P6.jpg");
        System.out.println(file.getName());
    }
}
